package com.simplehire.controller;

import com.simplehire.model.User;
import com.simplehire.model.UserPermission;
import com.simplehire.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.time.LocalDateTime;
import java.util.List;

@Controller
@RequestMapping("/admin/users")
@PreAuthorize("hasRole('ADMIN')") // 确保只有管理员可以访问
@RequiredArgsConstructor
public class UserManagementController {

    private final UserService userService;

    @GetMapping
    public String userManagement(Model model) {
        if (!model.containsAttribute("users")) {
            List<User> users = userService.getAllUsers();
            model.addAttribute("users", users);
        }
        model.addAttribute("user", new User());
        return "user-management";
    }

    @PostMapping
    public String createUser(@ModelAttribute User user, RedirectAttributes redirectAttributes) {
        try {
            userService.createUser(user);
            redirectAttributes.addFlashAttribute("success", "用户创建成功！");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/admin/users";
    }

    @PostMapping("/{id}")
    public String updateUser(@PathVariable Long id, @ModelAttribute User user, RedirectAttributes redirectAttributes) {
        try {
            userService.updateUser(id, user);
            redirectAttributes.addFlashAttribute("success", "用户更新成功！");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/admin/users";
    }

    @PostMapping("/{id}/delete")
    public String deleteUser(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            userService.deleteUser(id);
            redirectAttributes.addFlashAttribute("success", "用户删除成功！");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/admin/users";
    }

    @GetMapping("/{id}/permissions")
    public String getUserPermissions(@PathVariable Long id, Model model, RedirectAttributes redirectAttributes) {
        try {
            User user = userService.getUserById(id);
            List<UserPermission> permissions = userService.getUserPermissions(id);

            model.addAttribute("user", user);
            model.addAttribute("permissions", permissions);
            model.addAttribute("newPermission", new UserPermission());

            return "user-permissions";
        } catch (RuntimeException e) {
            // 如果用户不存在，捕获异常，添加错误信息并重定向
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/admin/users";
        }
    }

    @PostMapping("/{id}/permissions")
    public String addPermission(@PathVariable Long id,
                                @RequestParam String permission,
                                @RequestParam(required = false) LocalDateTime expiresAt,
                                RedirectAttributes redirectAttributes) {
        try {
            userService.addUserPermission(id, permission, expiresAt);
            redirectAttributes.addFlashAttribute("success", "权限添加成功！");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/admin/users/" + id + "/permissions";
    }

    // 修复后的方法，使用权限ID作为路径变量
    @PostMapping("/{userId}/permissions/{permissionId}/delete")
    public String removeUserPermissionById(
            @PathVariable Long userId,
            @PathVariable Long permissionId,
            RedirectAttributes redirectAttributes) {
        try {
            userService.removeUserPermissionById(userId, permissionId);
            redirectAttributes.addFlashAttribute("success", "权限删除成功！");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/admin/users/" + userId + "/permissions";
    }

    @GetMapping("/search")
    public String searchUsers(@RequestParam String keyword, Model model) {
        List<User> users = userService.searchUsers(keyword);
        model.addAttribute("users", users);
        model.addAttribute("searchKeyword", keyword);
        model.addAttribute("user", new User()); // 确保搜索结果页面也能创建新用户
        return "user-management";
    }
}
